import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Input, Select, DatePicker, Modal, Form, message } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FilterOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getOrders, createOrder, updateOrder, deleteOrder } from '../services/api';
import './Orders.css';

const { Option } = Select;
const { RangePicker } = DatePicker;

const Orders = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [dateRange, setDateRange] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  useEffect(() => {
    fetchOrders();
  }, []);

  const fetchOrders = async () => {
    setLoading(true);
    try {
      const data = await getOrders();
      setOrders(data);
    } catch (error) {
      message.error('获取订单失败');
      console.error('Failed to fetch orders:', error);
    }
    setLoading(false);
  };

  const handleSearch = () => {
    // 实现搜索功能
    let filteredOrders = [...orders];

    if (searchText) {
      filteredOrders = filteredOrders.filter(order => 
        order.orderNumber.toLowerCase().includes(searchText.toLowerCase()) ||
        order.customerName.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    if (statusFilter !== 'all') {
      filteredOrders = filteredOrders.filter(order => order.status === statusFilter);
    }

    if (dateRange.length) {
      const [startDate, endDate] = dateRange;
      filteredOrders = filteredOrders.filter(order => {
        const orderDate = new Date(order.orderDate);
        return orderDate >= startDate && orderDate <= endDate;
      });
    }

    // 这里只是演示，实际应该调用API进行服务端过滤
    setOrders(filteredOrders);
  };

  const handleReset = () => {
    setSearchText('');
    setStatusFilter('all');
    setDateRange([]);
    fetchOrders(); // 重置为原始数据
  };

  const showAddModal = () => {
    setCurrentOrder(null);
    form.resetFields();
    setIsModalOpen(true);
  };

  const showEditModal = (order) => {
    setCurrentOrder(order);
    form.setFieldsValue(order);
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      if (currentOrder) {
        await updateOrder(currentOrder.id, values);
        message.success('订单更新成功');
      } else {
        await createOrder(values);
        message.success('订单创建成功');
      }
      setIsModalOpen(false);
      fetchOrders();
    } catch (error) {
      message.error('操作失败，请重试');
      console.error('Failed to save order:', error);
    }
  };

  const handleDelete = async (id) => {
    try {
      await deleteOrder(id);
      message.success('订单删除成功');
      fetchOrders();
    } catch (error) {
      message.error('订单删除失败');
      console.error('Failed to delete order:', error);
    }
  };

  const columns = [
    {
      title: '订单编号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
      sorter: (a, b) => a.orderNumber.localeCompare(b.orderNumber),
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      sorter: (a, b) => a.customerName.localeCompare(b.customerName),
    },
    {
      title: '订单日期',
      dataIndex: 'orderDate',
      key: 'orderDate',
      sorter: (a, b) => new Date(a.orderDate) - new Date(b.orderDate),
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      sorter: (a, b) => a.amount - b.amount,
      render: (amount) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '全部', value: 'all' },
        { text: '待处理', value: 'pending' },
        { text: '已处理', value: 'processed' },
        { text: '已完成', value: 'completed' },
        { text: '已取消', value: 'cancelled' },
      ],
      onFilter: (value, record) => value === 'all' || record.status === value,
      render: (status) => {
        let statusClass = '';
        let statusText = '';

        switch (status) {
          case 'pending':
            statusClass = 'status-pending';
            statusText = '待处理';
            break;
          case 'processed':
            statusClass = 'status-processed';
            statusText = '已处理';
            break;
          case 'completed':
            statusClass = 'status-completed';
            statusText = '已完成';
            break;
          case 'cancelled':
            statusClass = 'status-cancelled';
            statusText = '已取消';
            break;
          default:
            statusClass = 'status-unknown';
            statusText = '未知';
        }

        return <span className={`status-tag ${statusClass}`}>{statusText}</span>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
            size="small"
          >
            编辑
          </Button>
          <Button
            type="danger"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
            size="small"
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="orders-container">
      <div className="orders-header">
        <h1>订单管理</h1>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={showAddModal}
        >
          添加订单
        </Button>
      </div>

      <div className="orders-filter">
        <div className="filter-item">
          <Input
            placeholder="搜索订单编号或客户名称"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            prefix={<SearchOutlined />}
            style={{ width: 250 }}
          />
        </div>

        <div className="filter-item">
          <Select
            placeholder="选择订单状态"
            value={statusFilter}
            onChange={setStatusFilter}
            style={{ width: 150 }}
          >
            <Option value="all">全部</Option>
            <Option value="pending">待处理</Option>
            <Option value="processed">已处理</Option>
            <Option value="completed">已完成</Option>
            <Option value="cancelled">已取消</Option>
          </Select>
        </div>

        <div className="filter-item">
          <RangePicker
            placeholder={['开始日期', '结束日期']}
            value={dateRange}
            onChange={(dates) => setDateRange(dates || [])}
            style={{ width: 250 }}
          />
        </div>

        <div className="filter-item">
          <Button
            icon={<FilterOutlined />}
            onClick={handleSearch}
          >
            筛选
          </Button>
          <Button onClick={handleReset} style={{ marginLeft: 8 }}>
            重置
          </Button>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={orders}
        loading={loading}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        className="orders-table"
      />

      <Modal
        title={currentOrder ? '编辑订单' : '添加订单'}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={currentOrder || {}}
        >
          <Form.Item
            name="orderNumber"
            label="订单编号"
            rules={[{ required: true, message: '请输入订单编号' }]}
          >
            <Input placeholder="请输入订单编号" />
          </Form.Item>

          <Form.Item
            name="customerName"
            label="客户名称"
            rules={[{ required: true, message: '请输入客户名称' }]}
          >
            <Input placeholder="请输入客户名称" />
          </Form.Item>

          <Form.Item
            name="orderDate"
            label="订单日期"
            rules={[{ required: true, message: '请选择订单日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="amount"
            label="订单金额"
            rules={[{ required: true, message: '请输入订单金额' }]}
          >
            <Input type="number" placeholder="请输入订单金额" />
          </Form.Item>

          <Form.Item
            name="status"
            label="订单状态"
            rules={[{ required: true, message: '请选择订单状态' }]}
          >
            <Select placeholder="请选择订单状态">
              <Option value="pending">待处理</Option>
              <Option value="processed">已处理</Option>
              <Option value="completed">已完成</Option>
              <Option value="cancelled">已取消</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Orders;